$(function () {
  let $commentBtn = $(".comment-btn");
  let $commentInput = $('.logged-comment').children("input");
  let $loginComment = $('.please-login-comment').children("input");
  let $commentList = $(".comment-list");
  // 发布评论的按钮
  $commentBtn.click(function () {
    $.post({
      url: '/news/add-comment/',
      data: {
        "content": $commentInput.val(),
        "news_id": $(this).data("news-id"),
      },
      success: res => {
        console.log(res["data"]);
        console.log(res);
        if (res["code"] === 0) {
          let data = res["data"];
          let comment = data["comment"];
          let pub_time = comment["pub_time"];
          let result = dateFormat(pub_time);
          let commentStr = `
            <li class="comment-item">
            <div class="comment-info clearfix">
              <img src="/static/images/avatar.jpeg" alt="avatar" class="comment-avatar">
              <span class="comment-user">${comment.author.username}</span>
              <span class="comment-pub-time">${result}</span>
            </div>
            <div class="comment-content">${comment.content}</div>
          </li>
          `;
          $commentList.prepend(commentStr);
          $commentInput.val('');
        } else if (res["code"] === 403) {
          window.message.showError(res["msg"]);
          setTimeout(() => {
            window.location.href = '/auth/login/';
          }, 2000)
        }
      },
      error: err => {
        logErr(err);
      }
    })
  });
  //
  $loginComment.focus(function () {
    $.post({
      url: '/news/add-comment/',
      success: res => {
        if (res["code"] === 403) {
          window.message.showError(res["msg"]);
          setTimeout(() => {
            window.location.href = '/auth/login/';
          }, 2000)
        }
      }
    })
  });


  $.get({
    url: "/news/comment/list/",
    data: {
      "news_id": $commentBtn.data("news-id"),
    },
    success: res => {
      if (res["code"] === 0) {
        let data = res["data"];
        let comments = data["comments"];
        comments.forEach(comment => {
          let pub_time = comment["pub_time"];
          let result = dateFormat(pub_time);
          let commentStr = `
            <li class="comment-item">
            <div class="comment-info clearfix">
              <img src="/static/images/avatar.jpeg" alt="avatar" class="comment-avatar">
              <span class="comment-user">${comment.author.username}</span>
              <span class="comment-pub-time">${result}</span>
            </div>
            <div class="comment-content">${comment.content}</div>
          </li>
          `;
          $commentList.prepend(commentStr);
        })
      }
    }
  })
});